//
//  CryptTool.swift
//  SwiftuiZsa
//
//  Created by hccc on 2023/11/17.
//

import Foundation
import CryptoSwift

class CryptTool {
    static let to = CryptTool(key: "psd4c45gw8er7a5t")
    private let key: [UInt8]
    
    init(key: String) {
        self.key = Array(key.utf8)
    }
    static func aesEncrypt(value: String) -> String? {
        do {
            let aes = try AES(key: to.key, blockMode: ECB(), padding: .pkcs7)
            let value = (try aes.encrypt(Array(value.utf8))).toBase64()
            return value
        } catch {
            return nil
        }
    }
    
    static func aesDecrypt(value: String) -> String? {
        do {
            let aes = try AES(key: to.key, blockMode: ECB(), padding: .pkcs7)
            let encrypted = Array<UInt8>(base64: value)
            let decrypted = try aes.decrypt(encrypted)
            return String(data: Data(decrypted), encoding: .utf8) ?? ""
        } catch {
            return nil
        }
    }
    
    static func base64Encode(_ plainText: String?) -> String? {
        if let plainData = plainText?.data(using: .utf8) {
            return plainData.base64EncodedString()
        }
        return nil
    }
    
    static func base64Decode(_ base64String: String) -> String? {
        if let decodedData = Data(base64Encoded: base64String) {
            return String(data: decodedData, encoding: .utf8)
        }
        return nil
    }
}
